//
//  ServerManager.swift
//  Server
//
//  Created by 叶情宇 on 2017/7/4.
//  Copyright © 2017年 叶情宇. All rights reserved.
//

import Cocoa
import SwiftSocket
class ServerManager: NSObject {
    fileprivate lazy var tcpServer:TCPServer = TCPServer(address: "127.0.0.1", port: 7888)
    fileprivate var isRuning : Bool = false
    fileprivate lazy var clients:[ClientManager] = [ClientManager]()

}
extension ServerManager{

    //开启服务器
    func startRuning(){
       //1.开启监听
      let rest =  tcpServer.listen()
      isRuning = true
      if rest.isSuccess {
            print("开启监听成功")
        }
       //2.开始接收
        DispatchQueue.global().async {
            while self.isRuning{
                if let client = self.tcpServer.accept(){
                   print("接收到一个客户端连接")
                    DispatchQueue.global().async {
                         self.handelClient(client)
                    }
                }
            }
        }
    }
    
    
    //关闭服务器
    func stopRuning(){
        isRuning = false

    }
}

extension ServerManager{

    fileprivate func handelClient(_ client:TCPClient){
        //1.保存客户端
      let clientManager =  ClientManager(client: client)
        clients.append(clientManager)
    
        //2.开始读取客户端信息
        clientManager.readMessage()
    }
}
